import { Button, Card, Checkbox, Form, Tree, message } from "antd";
import React from "react";
import styles from "./index.less"
import { fetchMenuTreeByAdmin } from "@/services/tenantManagement";
import { editSystemPlatformInfo, getSystemMenu, getSystemPlatformInfo } from "@/services/platformManagement";

const moduleNameList = ["robot",'moduleKefu','moduleTicket','largeLanguage'];
const qaNameList = ["qaKnowledge",'atlasKnowledge','dialogKnowledge','docKnowledge']

class FuncSetting extends React.Component{
  constructor(props){
    super(props);
    this.state = {
      menus:[],
      checkedKeys:[],
      loading:false,
      childrenNodes:[],
      allKfCenterChildrenIds:[]
    }
  }

  componentDidMount(){
    this.getInfo()
    this.getMenus()
  }

  getInfo = () => {
    this.setState({
      loading:true
    },async () => {
      const res = await getSystemPlatformInfo();
      this.setState({
        loading:false
      },() => {
        const moduleList = []
        const qaList = []
        for(const key in res){
          if(moduleNameList.indexOf(key) != -1 && res[key] == 1){
            moduleList.push(key)
          }
          if(qaNameList.indexOf(key) != -1 && res[key] == 1){
            qaList.push(key)
          }

          this.props.form.setFieldsValue({
            module:moduleList,
            qaType:qaList
          })
        }
      })     
    })
  }
  
  getMenus = async () => {
    const res = await getSystemMenu()
    const allKfCenterChildren = this.getAllChildrenNodes(res,'4')
    const allKfCenterChildrenIds = allKfCenterChildren.map(item => item.id)
    allKfCenterChildrenIds.push("4")
    this.setState({
      menus:res,
      allKfCenterChildrenIds
    },() => {
      
      this.getSelectMenu(res ? res : []);
    })
  }

  renderTreeNode = (data,flag) => {
    const module = this.props.form.getFieldValue("module")
    const qaType = this.props.form.getFieldValue("qaType")
    const { allKfCenterChildrenIds } = this.state;
    return data.map(item => {
      if(item.children){
        return (
          <Tree.TreeNode 
            title={item.name} 
            key={item.id} 
            disableCheckbox={
              module.indexOf("moduleKefu") === -1 
                && 
                (item.id == 36 || allKfCenterChildrenIds.indexOf(item.id) != -1)
              ||
              module.indexOf("moduleTicket") === -1 && item.id == 37
              ||
              qaType.indexOf("atlasKnowledge") === -1 && item.id == 26
              ||
              qaType.indexOf("dialogKnowledge") === -1 && item.id == 27
              ||
              module.indexOf("largeLanguage") === -1 && item.id == 124
            }
          >
            {this.renderTreeNode(item.children) }
          </Tree.TreeNode>
         
        )
      }else{
        return (
          <Tree.TreeNode 
            title={item.name} 
            key={item.id}
            disableCheckbox={
              module.indexOf("moduleKefu") === -1 
                && 
                (item.id == 36 || allKfCenterChildrenIds.indexOf(item.id) != -1)
              ||
              module.indexOf("moduleTicket") === -1 && item.id == 37
              ||
              qaType.indexOf("atlasKnowledge") === -1 && item.id == 26
              ||
              qaType.indexOf("dialogKnowledge") === -1 && item.id == 27
              ||
              module.indexOf("largeLanguage") === -1 && item.id == 124
            }
          />
        )
      }
    })
  }

  getSelectMenu = data => {
    const that = this;
    let { checkedKeys } = that.state;
    data.map(item => {
      if (item.children && item.children.length > 0) {
        const childrenChecked = item.children.filter(child => child.checked);
        if (childrenChecked.length === item.children.length) {
          checkedKeys.push(item.id);
        };
        that.getSelectMenu(item.children);
      } else {
        if (item.checked) {
          checkedKeys.push(item.id);
        }
      }
    });
    that.setState({ checkedKeys });
  }  

  changeModule = (value) => {
    const { menus,checkedKeys,allKfCenterChildrenIds } = this.state;
    const moduleKefuIndex = value.indexOf('moduleKefu');
    const moduleTicketIndex = value.indexOf('moduleTicket');
    const moduleLanguageIndex = value.indexOf("largeLanguage")
    let newList = checkedKeys
    //无IM 无账号中心-在线技能组-36/无客服中心-4
    if(moduleKefuIndex === -1){
      newList = newList.filter(item => item != 36 && item != 5 && allKfCenterChildrenIds.indexOf(item) === -1)
      // console.log('无IM',newList);
    }
    
    //无工单 无账号中心-工单技能组 -37
    if(moduleTicketIndex === -1){
      newList = newList.filter(item => item != 37 && item != 5 )
      // console.log('无工单',newList);
    }

    //无大语言模型 无机器人交互体验 无文档知识点
    if(moduleLanguageIndex === -1){
      newList = newList.filter(item => item != 124)
      const qaTypeList = this.props.form.getFieldValue("qaType");
      let newQaTypeList = qaTypeList.filter(item => item != 'docKnowledge')
      this.props.form.setFieldsValue({qaType:newQaTypeList})
      // console.log('无大语言',newList);
    }
    this.setState({
      checkedKeys:newList
    })
  }

  changeQaType = value => {
    const { menus,checkedKeys } = this.state;
    let newList = checkedKeys
    //无导图知识点 数据中心-知识导图统计-26
    if(value.indexOf('atlasKnowledge') === -1){
      newList = newList.filter(item => item != 26 && item != 3 )
    }
    //无多轮对话 数据中心-多轮对话统计
    if(value.indexOf('dialogKnowledge') === -1){
      newList = newList.filter(item => item != 27 && item != 3 )
    }
    this.setState({
      checkedKeys:newList
    })
  }

  onCheck = (checkedKeys, nodeInfo) => {
    console.log(nodeInfo);
    this.setState({ checkedKeys });
  };

  doSave = async () => {
    const { checkedKeys } = this.state;
    const info = this.props.form.getFieldsValue()
    let obj = {
      menuList:checkedKeys
    }
    for(const item of moduleNameList){
      if(info.module.indexOf(item) != -1){
        obj[item] = 1
      }else{
        obj[item] = 0
      }
    }
    for(const item of qaNameList){
      if(info.qaType.indexOf(item) != -1){
        obj[item] = 1
      }else{
        obj[item] = 0
      }
    }

    const res = await editSystemPlatformInfo(obj)
    message.info(res.message)
  }

  getAllChildrenNodes = (list, id, arr = []) => {
    for(let i in list) {
      if(list[i].id === id) {
        arr.push(list[i])
        if(list[i].children?.length > 0) {
          this.getChild(list[i].children, arr)
        }
      }else {
        if(list[i].children?.length > 0) {
          this.getAllChildrenNodes(list[i].children, id, arr)
        }
      }
    }
    return arr.filter(v => v.id !== id)
  }

  getChild = (list,  arr) => {
    list.forEach(v => {
      arr.push(v)
      if(v.children) {
        this.getChild(v.children, arr)
      }
    })
  }

  updateNodeInTree = (treeList,id, obj) => {
    if (!treeList || !treeList.length) {
      return;
    }
    for (let i = 0; i < treeList.length; i++) {
      if (treeList[i].id == id) {
        treeList[i]= obj;
        break;
      }
      updateNodeInTree(treeList[i].children,id,obj);
    }
  }

  render(){
    const { menus,checkedKeys,loading } = this.state;
    const { getFieldDecorator,getFieldValue } = this.props.form
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 3 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
      },
    };
    return(
      <Card loading={loading}>
        <Form {...formItemLayout}>
          <Form.Item label="功能模块设置">
            {getFieldDecorator("module", {
              rules: [
                { required: true, message: "请选择应用模块" },
              ],
              initialValue:['robot','moduleKefu','moduleTicket','largeLanguage']
            })(
              <Checkbox.Group onChange={this.changeModule}>
                <Checkbox value={'robot'} disabled>智能机器人</Checkbox>
                <Checkbox value={'moduleKefu'}>IM客服</Checkbox>
                <Checkbox value={'moduleTicket'}>工单系统</Checkbox>
                <Checkbox value={'largeLanguage'}>大语言模型</Checkbox>
              </Checkbox.Group>
            )}
              
          </Form.Item>
          <Form.Item label="知识类型设置">
            {getFieldDecorator("qaType", {
              rules: [
                { required: true, message: "请选择知识类型" },
              ],
              initialValue:['qaKnowledge','atlasKnowledge','dialogKnowledge','docKnowledge']
            })(
              <Checkbox.Group onChange={this.changeQaType}>
                <Checkbox value={'qaKnowledge'} disabled>问答型知识点</Checkbox>
                <Checkbox value={'atlasKnowledge'}>导图知识点</Checkbox>
                <Checkbox value={'dialogKnowledge'}>多轮对话</Checkbox>
                <Checkbox value={'docKnowledge'} disabled={getFieldValue("module").indexOf("largeLanguage") === -1}>文档型知识点</Checkbox>
              </Checkbox.Group>
            )}
          </Form.Item>
          <Form.Item label="系统菜单设置">
            <Tree checkable checkedKeys={checkedKeys} onCheck={this.onCheck}>
              {this.renderTreeNode(menus)}
            </Tree>
          </Form.Item>
          <Form.Item label=" " colon={false}>
            <Button type="primary" onClick={this.doSave}>保存</Button>
          </Form.Item>
        </Form>
      </Card>
    )
  }
}

export default Form.create()(FuncSetting)